package HibernateUtil;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * Hibernate4辅助类
 * @author Administrator
 *
 */
@SuppressWarnings("deprecation")
public final class HibernateUtil {
	
	/**
	 * 线程安全的全局对象
	 * 创建并打开Session
	 */
	private static final SessionFactory sessionFactory;
	/**
	 * 静态块，优先于无参构造函数
	 */
	static{
		/*
		 * sessionFactory = new Configuration().configure().buildSessionFactory(); 
		 * 这是hibernate3的用法，hibernate4已改变。
		 * */
		Configuration cfg = new Configuration();
		ServiceRegistry serviceR=null;
		try {
			 
			 
			 serviceR = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
			 
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			sessionFactory = cfg.configure().buildSessionFactory(serviceR);
		}
		
	}
	
	
	public static SessionFactory getSessionfactory() {
		return sessionFactory;
	}
	
	
}
